import 'dart:convert';
import 'dart:ui';
// import 'package:amap_location_fluttify/amap_location_fluttify.dart';
import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
import 'package:flutter_easyrefresh/material_footer.dart';
import 'package:flutter_easyrefresh/material_header.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:panda/base/Constant.dart';
import 'package:panda/entity/jiayouList_model.dart';
import 'package:panda/http/Api.dart';
import 'package:panda/http/HttpUtil.dart';
import 'package:panda/util/AppSaveInfoUtil.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:panda/util/LoadingUtil.dart';

import 'MapUtil.dart';
import 'jyz_detail_page.dart';

class JYZListPage extends StatefulWidget {
  @override
  _JYZListPageState createState() => _JYZListPageState();
}

class _JYZListPageState extends State<JYZListPage> {
  double _listHeight = ScreenUtil().setHeight(210); //单个列表高度
  int jyz_page = 1;
  var ip, rectangle;
  List<JYZModelData> jyzListData = []; //加油站数组
  EasyRefreshController _controller = new EasyRefreshController();
  String token = "", phone = "";
  double lat, lng;
  @override
  void initState() {
    super.initState();
    getString(TOKEN).then((value) {
      token = value;
      getString(PHONE).then((value) {
        phone = value;
        // getJYStationList(
        //     jyz_selectGasTypeItemValue,
        //     jyz_selectDistanceItemValue,
        //     jyz_selectoilNoItemValue,
        //     jyz_selectCondItemValue);
        // showDialog(
        // context: context,
        // barrierDismissible: false,
        // builder: (_) {
        //   return new NetLoadingDialog(
        //     loadingText: "定位中...",
        //     bgColor: Color.fromARGB(255, 0, 0, 0),
        //     requestCallBack: null,
        //     outsideDismiss: false,
        //   );
        // });

        // if (Platform.isIOS) {
        showDialog(
            context: context,
            barrierDismissible: false,
            builder: (_) {
              return new NetLoadingDialog(
                loadingText: "获取中...",
                bgColor: Color.fromARGB(255, 0, 0, 0),
                requestCallBack: null,
                outsideDismiss: false,
              );
            });
        //   // abloc();
        // } else {
        getLocation();
        // }
      });
    });
  }

  abloc() async {
    String url =
        "http://restapi.amap.com/v3/ip?key=d0074c75866e9e93643184a1c526db86";
    Response<String> response = await HttpUtil().get(url);
    // List s = response.data.split('jsonp_199126_(');
    // List s2 = s[1].split(')');
    Map userMap = json.decode(response.data);
    setState(() {
      if (userMap['status'].toString() == '1') {
        Navigator.of(context).pop(1);
        rectangle = userMap['rectangle'].toString().split(";")[1];
        lat = double.parse(rectangle.toString().split(",")[1]);
        lng = double.parse(rectangle.toString().split(",")[0]);
        // lat = double.parse(userMap['lat']);
        // lng = double.parse(userMap['lng']);
        // _refreshList();
        // empower();
        jyz_page = 1;
        getJYStationList(
            jyz_selectGasTypeItemValue,
            jyz_selectDistanceItemValue,
            jyz_selectoilNoItemValue,
            jyz_selectCondItemValue);
      } else {
        bloc();
      }
    });
  }

  bloc() async {
    String url = "https://ip.seeip.org/geoip";
    Response<String> response = await HttpUtil().get(url);
    Map userMap = json.decode(response.data);
    if (mounted) {
      setState(() {
        ip = userMap['ip'];
        cloc(ip);
      });
    }
  }

  cloc(String theip) async {
    String url =
        'https://restapi.amap.com/v3/ip?output=json&key=fc9ab3e41e05ebc633244a07a83e1b1f&ip=' +
            theip;
    Response<String> response = await HttpUtil().get(url);
    Map userMap = json.decode(response.data);
    Navigator.of(context).pop(1);
    setState(() {
      if (userMap['status'].toString() == '1') {
        List s = userMap['rectangle'].toString().split(';');
        rectangle = s[0];
        lat = double.parse(rectangle.toString().split(",")[1]);
        lng = double.parse(rectangle.toString().split(",")[0]);
        // _refreshList();
        jyz_page = 1;
        getJYStationList(
            jyz_selectGasTypeItemValue,
            jyz_selectDistanceItemValue,
            jyz_selectoilNoItemValue,
            jyz_selectCondItemValue);
        //  lat = userMap['latitude'];
        // lng = userMap['longitude'];
      }
    });
  }

  getLocation() async {
    // final location = await AmapLocation.fetchLocation();
    // // var loc = new Jlocation();
    // Navigator.of(context).pop(1);
    // // loc.onLocationChanged().listen((loc) {
    // //   // Navigator.of(context).pop(1);
    // // setState(() {
    // //   if (!mounted) return;
    // lat = location.latLng.latitude;
    // lng = location.latLng.longitude;
    // Fluttertoast.showToast(msg: lat.toString()+"  "+lng.toString());
    // print(location.latLng);
    jyz_page = 1;
    getJYStationList(jyz_selectGasTypeItemValue, jyz_selectDistanceItemValue,
        jyz_selectoilNoItemValue, jyz_selectCondItemValue);
    // });
  }

  //加油站参数
  List<DropdownMenuItem> jyz_distanceItemList() {
    List<DropdownMenuItem> items = new List();
    DropdownMenuItem item1 = new DropdownMenuItem(
        value: '1000',
        child: new Text(
          '1千米',
          style: TextStyle(
            fontSize: 14,
          ),
          textAlign: TextAlign.center,
        ));
    DropdownMenuItem item2 = new DropdownMenuItem(
        value: '3000',
        child: new Text(
          '3千米',
          style: TextStyle(
            fontSize: 14,
          ),
          textAlign: TextAlign.center,
        ));
    DropdownMenuItem item3 = new DropdownMenuItem(
        value: '5000',
        child: new Text(
          '5千米',
          style: TextStyle(
            fontSize: 14,
          ),
          textAlign: TextAlign.center,
        ));
    DropdownMenuItem item4 = new DropdownMenuItem(
        value: '10000',
        child: new Text(
          '10千米',
          style: TextStyle(
            fontSize: 14,
          ),
          textAlign: TextAlign.center,
        ));
    items.add(item1);
    items.add(item2);
    items.add(item3);
    items.add(item4);
    return items;
  }

  var jyz_selectDistanceItemValue = '50000';

  List<DropdownMenuItem> jyz_oilNotemList() {
    List<DropdownMenuItem> items = new List();
    DropdownMenuItem item1 = new DropdownMenuItem(
        value: '92',
        child: new Text(
          '#92',
          style: TextStyle(
            fontSize: 14,
          ),
          textAlign: TextAlign.center,
        ));
    DropdownMenuItem item2 = new DropdownMenuItem(
        value: '95',
        child: new Text(
          '#95',
          style: TextStyle(
            fontSize: 14,
          ),
          textAlign: TextAlign.center,
        ));
    DropdownMenuItem item3 = new DropdownMenuItem(
        value: '98',
        child: new Text(
          '#98',
          style: TextStyle(
            fontSize: 14,
          ),
          textAlign: TextAlign.center,
        ));
    DropdownMenuItem item4 = new DropdownMenuItem(
        value: '0',
        child: new Text(
          '#0',
          style: TextStyle(
            fontSize: 14,
          ),
          textAlign: TextAlign.center,
        ));
    items.add(item1);
    items.add(item2);
    items.add(item3);
    items.add(item4);
    return items;
  }

  var jyz_selectoilNoItemValue;

  // List<DropdownMenuItem> jyz_condtemList() {
  //   List<DropdownMenuItem> items = new List();
  //   DropdownMenuItem item1 = new DropdownMenuItem(
  //       value: '1',
  //       child: new Text(
  //         '油价升序',
  //         style: TextStyle(
  //           fontSize: 14,
  //         ),
  //         textAlign: TextAlign.center,
  //       ));
  //   // DropdownMenuItem item2 = new DropdownMenuItem(
  //   //     value: '2',
  //   //     child: new Text(
  //   //       '距离升序',
  //   //       style: TextStyle(
  //   //         fontSize: 14,
  //   //       ),
  //   //       textAlign: TextAlign.center,
  //   //     ));
  //   items.add(item1);
  //   // items.add(item2);
  //   return items;
  // }

  var jyz_selectCondItemValue;

  List<DropdownMenuItem> jyz_gasTypetemList() {
    List<DropdownMenuItem> items = new List();
    DropdownMenuItem item1 = new DropdownMenuItem(
        value: '1',
        child: new Text(
          '中石油',
          style: TextStyle(
            fontSize: 14,
          ),
          textAlign: TextAlign.center,
        ));
    DropdownMenuItem item2 = new DropdownMenuItem(
        value: '2',
        child: new Text(
          '中石化',
          style: TextStyle(
            fontSize: 14,
          ),
          textAlign: TextAlign.center,
        ));
    DropdownMenuItem item3 = new DropdownMenuItem(
        value: '3',
        child: new Text(
          '壳牌',
          style: TextStyle(
            fontSize: 14,
          ),
          textAlign: TextAlign.center,
        ));
    DropdownMenuItem item4 = new DropdownMenuItem(
        value: '4',
        child: new Text(
          '其他',
          style: TextStyle(
            fontSize: 14,
          ),
          textAlign: TextAlign.center,
        ));
    items.add(item1);
    items.add(item2);
    items.add(item3);
    items.add(item4);
    return items;
  }

  var jyz_selectGasTypeItemValue;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: mainColor,
        title: Text(
          '熊猫加油',
          style: TextStyle(
              fontSize: ScreenUtil.getInstance().setSp(BIG_FONT_SIZE)),
        ),
      ),
      backgroundColor: f0Color,
      body: new Stack(
        children: <Widget>[
          Container(
              color: f0Color,
              margin: EdgeInsets.fromLTRB(0, ScreenUtil().setHeight(80), 0, 0),
              child: EasyRefresh(
                  header: MaterialHeader(),
                  footer: MaterialFooter(),
                  controller: _controller,
                  child: CustomScrollView(slivers: <Widget>[
                    SliverToBoxAdapter(child: Container()),
                    SliverFixedExtentList(
                        delegate: _buildTypeList(), itemExtent: _listHeight),
                    SliverToBoxAdapter(
                      child: Container(),
                    ),
                  ]),
                  onRefresh: () async {
                    _refreshList();
                  },
                  onLoad: () async {
                    jyz_page++;
                    getJYStationList(
                        jyz_selectGasTypeItemValue,
                        jyz_selectDistanceItemValue,
                        jyz_selectoilNoItemValue,
                        jyz_selectCondItemValue);
                  })),
          _buildPopHeader()
        ],
      ),
    );
  }

  SliverChildDelegate _buildTypeList() {
    return SliverChildBuilderDelegate(_buildListItem,
        childCount: jyzListData.length);
  }

  _buildPopHeader() {
    //条件筛选头部
    var jyz_header = Container(
      color: white,
      // margin: EdgeInsets.only(
      //     top: ScreenUtil().setHeight(20), bottom: ScreenUtil().setHeight(20)),
      height: ScreenUtil().setHeight(80),
      width: MediaQuery.of(context).size.width,
      child: Row(
        children: <Widget>[
          Expanded(
              flex: 1,
              child: Container(
                alignment: Alignment.center,
                child: new DropdownButtonHideUnderline(
                  child: new DropdownButton(
                    iconSize: 20.0,
                    hint: new Text(
                      '油号编码',
                      style: TextStyle(
                        fontSize:
                            ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE),
                      ),
                      textAlign: TextAlign.center,
                    ),
                    value: jyz_selectoilNoItemValue,
                    items: jyz_oilNotemList(),
                    onChanged: (T) {
                      setState(() {
                        jyz_selectoilNoItemValue = T;
                        _refreshList();
                      });
                    },
                  ),
                ),
              )),
          Expanded(
              flex: 1,
              child: Container(
                alignment: Alignment.center,
                child: new DropdownButtonHideUnderline(
                  child: new DropdownButton(
                    iconSize: 20.0,
                    hint: new Text(
                      '默认距离',
                      style: TextStyle(
                        fontSize:
                            ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE),
                      ),
                      textAlign: TextAlign.center,
                    ),
                    value: jyz_selectDistanceItemValue,
                    items: jyz_distanceItemList(),
                    onChanged: (T) {
                      setState(() {
                        jyz_selectDistanceItemValue = T;
                        _refreshList();
                      });
                    },
                  ),
                ),
              )),
          // Expanded(
          //     flex: 1,
          //     child: Container(
          //       alignment: Alignment.center,
          //       child: new DropdownButtonHideUnderline(
          //         child: new DropdownButton(
          //           iconSize: 20.0,
          //           hint: new Text(
          //             '价格排序',
          //             style: TextStyle(
          //               fontSize:
          //                   ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE),
          //             ),
          //             textAlign: TextAlign.center,
          //           ),
          //           value: jyz_selectCondItemValue,
          //           items: jyz_condtemList(),
          //           onChanged: (T) {
          //             setState(() {
          //               jyz_selectCondItemValue = T;
          //               _refreshList();
          //             });
          //           },
          //         ),
          //       ),
          //     )),
          Expanded(
              flex: 1,
              child: Container(
                alignment: Alignment.center,
                child: new DropdownButtonHideUnderline(
                  child: new DropdownButton(
                    iconSize: 20.0,
                    hint: new Text(
                      '全部类型',
                      style: TextStyle(
                        fontSize:
                            ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE),
                      ),
                      textAlign: TextAlign.center,
                    ),
                    value: jyz_selectGasTypeItemValue,
                    items: jyz_gasTypetemList(),
                    onChanged: (T) {
                      setState(() {
                        jyz_selectGasTypeItemValue = T;
                        _refreshList();
                      });
                    },
                  ),
                ),
              ))
        ],
      ),
    );
    return jyz_header;
  }

/***************************加油站数据列表**************************/
  Widget _buildListItem(BuildContext context, int index) {
    return new GestureDetector(
        onTap: () {
          //处理点击事件
          JYZModelData model = jyzListData[index];
          // var gasIds=model.gasid;
          Navigator.push(
              context,
              MaterialPageRoute(
                  //导航打开新视图
                  builder: (context) =>
                      JYZDetailPage(model: model) //打开第二个页面，并传值，传�����值的名称是model
                  ));
        },
        child: Container(
            decoration: BoxDecoration(
                color: white, borderRadius: BorderRadius.circular(10)),
            padding: EdgeInsets.all(ScreenUtil().setHeight(13)),
            // margin: EdgeInsets.fromLTRB(ScreenUtil().setHeight(15),
            //     ScreenUtil().setHeight(15), ScreenUtil().setHeight(15), 0),
            child: Column(
              children: <Widget>[
                Row(children: <Widget>[
                  _leftImage(index),
                  Expanded(
                    child: _rightColumn(index),
                  )
                ], crossAxisAlignment: CrossAxisAlignment.start),
                // Divider(
                //   height: 1,
                // )
              ],
            )));
  }

  Widget _pd(Widget w, {double l, double t, double r, double b}) {
    //边距
    return Padding(
        padding: EdgeInsets.fromLTRB(
            ScreenUtil().setWidth(l) ?? 0,
            ScreenUtil().setHeight(t) ?? 0,
            ScreenUtil().setWidth(r) ?? 0,
            ScreenUtil().setHeight(b) ?? 0),
        child: w);
  }

  Widget _leftImage(int index) {
    //左图
    var image = new Image(
        image: NetworkImage(jyzListData[index].gaslogosmall),
        width: ScreenUtil().setHeight(150),
        height: ScreenUtil().setHeight(150),
        fit: BoxFit.fill);
    return image;
  }

  Widget _rightColumn(int index) {
    //右内容
    var title = Text(
      jyzListData[index].gas_name,
      style: TextStyle(
          color: Colors.black,
          fontSize: ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE + 3)),
      maxLines: 2,
      overflow: TextOverflow.ellipsis,
    );
    var price = RichText(
      text: TextSpan(style: TextStyle(color: Colors.red), children: [
        TextSpan(text: '¥', style: TextStyle(fontSize: 12.0)),
        TextSpan(
            text: jyzListData[index].priceyfq,
            style: TextStyle(fontSize: 18.0)),
        TextSpan(
            text: '/升/' + jyzListData[index].oil_name,
            style: TextStyle(fontSize: 12.0)),
      ]),
      maxLines: 1,
      overflow: TextOverflow.ellipsis,
    );
    var distance = RichText(
      text: TextSpan(style: TextStyle(fontSize: 13.0), children: [
        TextSpan(
            text: formatNum(
                    double.parse((jyzListData[index].distance == "null"
                            ? "0"
                            : jyzListData[index].distance)) /
                        1000,
                    2) +
                "Km       ",
            style: TextStyle(color: Colors.grey)),
        TextSpan(
            text: '导航',
            style: TextStyle(
                color: Colors.orange,
                fontSize: ScreenUtil.getInstance().setSp(SMALL_FONT_SIZE))),
      ]),
    );
    var address = Text(
      jyzListData[index].provincename +
          jyzListData[index].cityname +
          jyzListData[index].countyname +
          jyzListData[index].gasaddress,
      style: TextStyle(
          color: Colors.grey,
          fontSize: ScreenUtil.getInstance().setSp(SMALL_FONT_SIZE)),
      maxLines: 1,
      overflow: TextOverflow.ellipsis,
    );
    return new Column(
      children: <Widget>[
        _pd(title, l: 10, t: 0, r: 10, b: 0),
        Row(
          children: <Widget>[
            _pd(price, l: 10, t: 0, r: 10, b: 8),
            GestureDetector(
              child: distance,
              onTap: () async {
                var result = await showModalBottomSheet(
                    context: context,
                    builder: (context) {
                      return Container(
                        height:
                            // Platform.isIOS
                            //     ? ScreenUtil.getInstance().setHeight(DP_200 + 40) +
                            //         2
                            //     :
                            ScreenUtil.getInstance().setHeight(DP_160) +
                                1, //配置底部弹出框高度
                        child: Column(
                          children: <Widget>[
                            GestureDetector(
                              behavior: HitTestBehavior.opaque,
                              child: Container(
                                height:
                                    ScreenUtil.getInstance().setHeight(DP_80),
                                alignment: Alignment.center,
                                child: Text('百度地图',
                                    style: TextStyle(
                                        fontSize: ScreenUtil.getInstance()
                                            .setSp(NORMAL_FONT_SIZE))),
                              ),
                              onTap: () {
                                Navigator.pop(context, '1');
                              },
                            ),
                            Container(
                              height: 1,
                              color: f0Color,
                            ),
                            GestureDetector(
                              behavior: HitTestBehavior.opaque,
                              child: Container(
                                height:
                                    ScreenUtil.getInstance().setHeight(DP_80),
                                alignment: Alignment.center,
                                child: Text('高德地图',
                                    style: TextStyle(
                                        fontSize: ScreenUtil.getInstance()
                                            .setSp(NORMAL_FONT_SIZE))),
                              ),
                              onTap: () {
                                Navigator.pop(context, '2');
                              },
                            ),
                            // Offstage(
                            //   offstage: !Platform.isIOS,
                            //   child: Container(
                            //     height: 1,
                            //     color: f0Color,
                            //   ),
                            // ),
                            // Offstage(
                            //   offstage: !Platform.isIOS,
                            //   child: GestureDetector(
                            //     behavior: HitTestBehavior.opaque,
                            //     child: Container(
                            //       height:
                            //           ScreenUtil.getInstance().setHeight(DP_80),
                            //       alignment: Alignment.center,
                            //       child: Text('苹果地图',
                            //           style: TextStyle(
                            //               fontSize: ScreenUtil.getInstance()
                            //                   .setSp(NORMAL_FONT_SIZE))),
                            //     ),
                            //     onTap: () {
                            //       Navigator.pop(context, '3');
                            //     },
                            //   ),
                            // ),
                          ],
                        ),
                      );
                    });
                if ("1" == result) {
                  MapUtil.gotoBaiduMap(jyzListData[index].gasaddresslongitude,
                      jyzListData[index].gasaddresslatitude);
                } else if ("2" == result) {
                  MapUtil.gotoAMap(jyzListData[index].gasaddresslongitude,
                      jyzListData[index].gasaddresslatitude);
                }
              },
            )
          ],
        ),
        Container(
          margin: EdgeInsets.only(
              left: ScreenUtil.getInstance().setHeight(DP_10), bottom: 6),
          width: ScreenUtil.getInstance().setHeight(DP_120 + 10),
          height: ScreenUtil.getInstance().setHeight(DP_30 + 2),
          decoration:
              BoxDecoration(border: Border.all(width: 1, color: mainColor)),
          child: Row(
            children: <Widget>[
              Container(
                  height: ScreenUtil.getInstance().setHeight(DP_30 + 2),
                  color: mainColor,
                  child: Icon(Icons.arrow_downward,
                      color: white, size: ScreenUtil.getInstance().setSp(40))),
                      Expanded(
                        child:Text(
                          " 直降" +formatNum(
                                  double.parse(jyzListData[index].pricegun) -
                                      double.parse(jyzListData[index].priceyfq),
                                  2),
                          style: TextStyle(
                            color: mainColor,
                            fontSize:
                              ScreenUtil.getInstance().setSp(SMALL_FONT_SIZE))
                          )
                      ),
            ],
          ),
        ),
        _pd(address, l: 10, t: 0, r: 10, b: 8)
      ],
      crossAxisAlignment: CrossAxisAlignment.start,
    );
  }

  @override
  void dispose() {
    // AMapLocationClient.shutdown();
    super.dispose();
  }

  void _refreshList() {
    jyz_page = 1;
    getJYStationList(jyz_selectGasTypeItemValue, jyz_selectDistanceItemValue,
        jyz_selectoilNoItemValue, jyz_selectCondItemValue);
  }

/*获取列表数据*/
  getJYStationList(gasType, distinct, oilNo, cond) async {
    //加油站
    FormData data;
    if (lat == null) {
      data = new FormData.fromMap({
        'token': token,
        'gasType': gasType,
        'phone': phone,
        'distinct': distinct,
        'page': jyz_page,
        'per': '8',
        'oilNo': oilNo, //油号编码
        'cond': cond
      });
    } else {
      data = new FormData.fromMap({
        'token': token,
        'gasType': gasType,
        'phone': phone,
        'lng_lat': lng.toString() + "," + lat.toString(),
        'distinct': distinct,
        'page': jyz_page,
        'per': '8',
        'oilNo': oilNo, //油号编码
        'cond': cond
      });
    }
    Response<String> response =
        await HttpUtil().post(Api.JIAYOULIST, data: data);
    Map userMap = json.decode(response.data);
    JYZModelEntity jyzEntity = new JYZModelEntity.fromJson(userMap);
    if (jyzEntity.code == 0) {
      if (mounted) {
        setState(() {
          if (jyz_page == 1) {
            jyzListData.clear();
            jyzListData = jyzEntity.data;
            _controller.finishRefresh();
            _controller.resetLoadState();
          } else {
            jyzListData.addAll(jyzEntity.data);
            _controller.finishLoad(noMore: jyzEntity.data.length == 0);
          }
        });
      }
    }
  }

  String formatNum(double num, int postion) {
    if ((num.toString().length - num.toString().lastIndexOf(".") - 1) <
        postion) {
      return num.toStringAsFixed(postion)
          .substring(0, num.toString().lastIndexOf(".") + postion + 1)
          .toString();
    } else {
      return num.toString()
          .substring(0, num.toString().lastIndexOf(".") + postion + 1)
          .toString();
    }
  }
}
